import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mahjong/card_entity.dart';
import 'package:mahjong/util/CardUtil.dart';
import 'package:orientation/orientation.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  OrientationPlugin.setPreferredOrientations(
      [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
  OrientationPlugin.setEnabledSystemUIOverlays([]);
  SystemChrome.setEnabledSystemUIOverlays([]);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: '万州麻将'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<CardEntity> cardEntityList = [];

  List<CardEntity> exportCardEntityList = [];

  List<int> allCardList = [];

  List<int> huCardList = [];
  AudioCache advancedPlayer = AudioCache();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  void initCardList() {
    exportCardEntityList.clear();
    allCardList.clear();
    cardEntityList.clear();
    for (int i = 1; i <= 27; i++) {
      for (int j = 1; j <= 4; j++) {
        allCardList.add(i);
      }
    }
    allCardList.shuffle();

    for (int i = allCardList.length - 1, j = 0; j < 13; i--) {
      var cardId = allCardList[i];
      cardEntityList.add(CardEntity.init(cardId: cardId));
      allCardList.removeAt(i);
      j++;
    }
    cardEntityList.sort((a, b) {
      return a.cardId - b.cardId;
    });
    setState(() {});
  }

  void shuffleCards(List<CardEntity> cardList) {
    cardList.sort((a, b) {
      return a.cardId - b.cardId;
    });
  }

  void removeCard(List<CardEntity> cardList, int cardId) {
    for (int i = 0, j = cardList.length - 1; i <= j; i++) {
      if (cardList[i].cardId == cardId) {
        cardList.removeAt(i);
        break;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    /* List<int> huCard = Cardutil.hu([1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9]);
    if (huCard.length == 0) {
      print("你没有可以胡的牌");
    } else {
      print("你可以胡以下牌");
      huCard.forEach((val) {
        print("," + val.toString());
      });
    } */
    return Scaffold(
        body: SafeArea(
      child: Stack(
        children: [
          Positioned(
              child: Container(
            width: double.infinity,
            child: Image.asset(
              "images/mahjong/prepare_zhuomian.jpg",
              fit: BoxFit.fill,
            ),
          )),
          Positioned(
              top: 0,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height / 100 * 5,
                child: Wrap(children: initAllcardView()),
              )),
          Positioned(
              bottom: MediaQuery.of(context).size.width / 16 * 1.8,
              left: MediaQuery.of(context).size.width / 2 / 2 / 2,
              child: InkWell(
                child: Container(
                  width: MediaQuery.of(context).size.height / 12,
                  height: MediaQuery.of(context).size.height / 12,
                  child: Image.asset(
                    "images/mahjong/tips.png",
                    fit: BoxFit.fill,
                  ),
                ),
                onTap: () {
                  huCardList = Cardutil.huCards(
                      cardEntityList.map((e) => e.cardId).toList());
                  showDialog<Null>(
                    context: context,
                    barrierDismissible: false,
                    builder: (BuildContext context) {
                      return new AlertDialog(
                        content: huCardList.length > 0
                            ? Wrap(
                                children: buildUserExportCards(huCardList
                                    .map((e) => CardEntity.init(
                                        cardId: e,
                                        cardBackGround:
                                            'images/mahjong/bg_p0_oper_f.png',
                                        isExport: true,
                                        cardWidthScale:
                                            MediaQuery.of(context).size.width /
                                                30))
                                    .toList()))
                            : Text("暂无胡牌"),
                        actions: <Widget>[
                          new FlatButton(
                            child: new Text('确定'),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                          ),
                        ],
                      );
                    },
                  ).then((val) {
                    print(val);
                  });
                },
              )),

          // 主玩家的 出牌情况
          Positioned(
              top: MediaQuery.of(context).size.height / 100 * 55,
              left: MediaQuery.of(context).size.width / 2 / 2,
              child: Container(
                width: MediaQuery.of(context).size.width / 2,
                height: MediaQuery.of(context).size.height / 100 * 5,
                child:
                    Wrap(children: buildUserExportCards(exportCardEntityList)),
              )),
          Positioned(
              bottom: 0.00,
              left: 0.0,
              child: Container(
                  alignment: Alignment.bottomLeft,
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: buildUserCards(cardEntityList)))),
          Positioned(
              bottom: 0,
              right: 0,
              child: MaterialButton(
                color: Colors.blue,
                textColor: Colors.white,
                child: new Text('重新洗牌'),
                onPressed: () {
                  initCardList();
                },
              )),
        ],
      ),
    ));
  }

  List<Widget> buildUserCards(List<CardEntity> cardEntityList) {
    List<Widget> resultList = [];
    for (int i = 0, j = cardEntityList.length; i < j; i++) {
      if (i == j - 1) {
        resultList
            .add(SizedBox(width: MediaQuery.of(context).size.width / 16 / 2));
        resultList.add(buildCard(cardEntityList[i]));
      } else {
        resultList.add(buildCard(cardEntityList[i]));
      }
    }
    return resultList;
  }

  List<Widget> buildUserExportCards(List<CardEntity> cardEntityList) {
    List<Widget> resultList = [];
    for (int i = 0, j = cardEntityList.length; i < j; i++) {
      resultList.add(buildCard(cardEntityList[i]));
    }
    return resultList;
  }

  Widget buildCard(CardEntity entity) {
    return Draggable(
        onDraggableCanceled: (Velocity velocity, Offset offset) {
          //松手的时候
          setState(() {
            print(offset);
          });
        },
        feedback: buildCardContainer(entity),
        child: GestureDetector(
            onTap: () {
              entity.cardTop = entity.cardTop > 0 ? 0.00 : 20.00;
              print(entity.cardTop);
              setState(() {});
            },
            onDoubleTap: () {
              advancedPlayer
                  .play('sounds/' + entity.cardId.toString() + "s.ogg");
              exportCardEntityList.add(CardEntity.init(
                  cardId: entity.cardId,
                  cardBackGround: 'images/mahjong/bg_p0_oper_f.png',
                  isExport: true,
                  cardWidthScale: MediaQuery.of(context).size.width / 30));
              removeCard(cardEntityList, entity.cardId);
              cardEntityList.add(CardEntity.init(cardId: allCardList.last));
              allCardList.removeLast();
              shuffleCards(cardEntityList);
              setState(() {});
            },
            child: buildCardContainer(entity)));
  }

  Widget buildCardContainer(CardEntity entity) {
    // 玩家的手牌应该将屏幕分为 16等分
    entity.cardWidth =
        MediaQuery.of(context).size.width / entity.cardWidthScale;
    return Column(
      children: [
        Container(
          height: entity.cardWidth * 1.46,
          width: entity.cardWidth,
          child: Stack(
            children: [
              Container(
                  width: double.infinity,
                  height: double.infinity,
                  //margin: EdgeInsets.only(left: 5.00),
                  child: Image.asset(
                    entity.cardBackGround,
                    fit: BoxFit.cover,
                  )),
              Positioned(
                  top: entity.isExport
                      ? entity.cardWidth * 1.46 * 0.1
                      : entity.cardWidth * 1.46 * 0.2,
                  left: entity.isExport
                      ? entity.cardWidth * 0.15
                      : entity.cardWidth * 0.1,
                  child: Container(
                      width: entity.isExport
                          ? entity.cardWidth * 0.7
                          : entity.cardWidth * 0.8,
                      height: entity.isExport
                          ? entity.cardWidth * 0.7 * 1.27
                          : entity.cardWidth * 0.8 * 1.27,
                      child: Image.asset(
                        'images/mahjong/south_hand_tile_' +
                            entity.cardId.toString() +
                            '.png',
                        //width: entity.cardWidth,
                        fit: BoxFit.cover,
                      ))),
            ],
          ),
        ),
        entity.cardTop == 0 ? SizedBox() : SizedBox(height: 20.00)
      ],
    );
  }

  List<Widget> initAllcardView() {
    List<int> result = [];
    for (int i = allCardList.length - 1; i >= 0; i--) {
      result.add(allCardList[i]);
    }

    return buildUserExportCards(result
        .map((e) => CardEntity.init(
            cardId: e,
            cardBackGround: 'images/mahjong/bg_p0_oper_f.png',
            isExport: true,
            cardWidthScale: MediaQuery.of(context).size.width / 30))
        .toList());
  }
}
